<script lang="ts" setup>
import { onMounted, reactive, watch } from 'vue'

const emit = defineEmits(['update:modelValue', 'change'])
const props = defineProps({
  start: {
    type: String,
    default: ''
  },
  end: {
    type: String,
    default: ''
  },
  modelValue: {
    type: [Number, String],
    default: ''
  },
  number: {
    type: Boolean,
    default: true
  },
  max: {
    type: Number,
    default: 999999999
  },
  min: {
    type: Number,
    default: 0
  }
})

const state = reactive({
  value: ''
})

const initValue = (value:any) => {
  const _val = parseFloat(value)
  state.value = isNaN(_val) ? value : _val
}

watch(() => state.value, (val:any, old:any) => {
  changeLocalValue(val, old)
})

watch(() => props.modelValue, (val:any) => {
  initValue(val)
})
onMounted(() => {
  initValue(props.modelValue)
})


const changeLocalValue = (val:any, old:any) => {
  if (!val || typeof val === 'number') return
  const index = val.indexOf('.')
  if (index === val.lastIndexOf('.') && index === val.length - 1) return
  // const _val:any = parseFloat(val)
  if(parseFloat(val)>0){
  state.value = isNaN(parseFloat(val)) ? old : parseFloat(val)
  }else{
    state.value = val
  }
}

const validLimit = (val:number):any => {
  if (val < props.min) { val = props.min } else if (val > props.max) { val = props.max }
  return val
}

const blurHandler = () => {
  let _val:any = parseFloat(state.value)
  if (isNaN(_val))_val = props.number ? 0 : ''
  else _val = validLimit(_val)
  changeHandler(_val)
}

const changeHandler = (val:any) => {
  state.value = val
  emit('update:modelValue', val)
  emit('change', val)
}
</script>

<template>
  <el-input v-model="state.value"
            maxlength="9"
            @change="blurHandler">
    <template #prefix>
      <slot name="prefix">
        <span v-if="start">{{ start }}</span>
      </slot>
    </template>
    <template #suffix>
      <slot name="suffix">
        <span v-if="end">{{ end }}</span>
      </slot>
    </template>
  </el-input>
</template>

<style scoped lang="scss">
</style>
